/**
 * Created by WebStorm.
 * User: NiRongxu
 * Date: 2022/4/11
 * Description: 文件描述
 */
import {reactive, toRefs,toRaw} from 'vue'
import { defineStore } from 'pinia'
import router, {defaultRouter, addRouter, IRouter} from '@/router'
import {RouteRecordRaw} from 'vue-router'
interface IrouterDataList {
  routers: RouteRecordRaw[]
  // addRouters: RouteRecordRaw[]
  role:any
}

export const routerDataStore = defineStore('routerDataStore', () => {
  // let routers = reactive<Array<RouteRecordRaw>>([]) // 每次刷新都要通过token请求个人信息来筛选动态路由
  // let addRouters = reactive<Array<RouteRecordRaw>>([]) // 每次刷新都要通过token请求个人信息来筛选动态路由

  const routerDataList = reactive<IrouterDataList>({
    routers: [],
    role:[]
    // addRouters: []
  })

  function setRouters(routerArr: Array<IRouter>) {

    routerDataList.routers = defaultRouter.concat(routerArr) // 所有有权限的路由表，用来生成菜单列表
    // routerDataList.addRouters = routerArr // 保存动态路由用来addRouter
    
    routerArr.forEach((item) => {
      router.addRoute(item)
    })
    
  }


  
  function newRoutes(r: string) { // 切换角色，测试权限管理
    routerDataList.role=r
    const addRouters=toRaw([...addRouter])
    //  通过递归路由表，删除掉没有权限的路由
    function eachSelect(routers: Array<IRouter>, userRole: string) {
      return  routers.filter(item=>{
        const role: any =item.meta?.role
        if (role?.length && !userRole.includes(role[0])) {
          return false
        }
        if (item?.children?.length) {
          item.children=eachSelect(item.children!, userRole)
        }
         return true
      })
    }

    let arr= eachSelect(addRouters, r)
    
     setRouters(arr)
     
  }

  return { ...toRefs(routerDataList), newRoutes }

})


